<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <!-- 输入框 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryUserInfo.query"
            clearable
            @clear="clearValueInfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="4">
          <el-button
            type="primary"
            @click="dialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表渲染 -->
      <el-table
        :data="usersList"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column
          type="index"
          label="#"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
        ></el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
        >
          <!-- 使用作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserModel(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUsers(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryUserInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryUserInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
        @close="addDialogClosed"
      >
        <!-- 内容主题区域 :modle数据绑定对象 -->
        <el-form
          :model="addRuleForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <!-- 用户名 -->
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input v-model="addRuleForm.username"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input v-model="addRuleForm.password"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="addRuleForm.email"></el-input>
          </el-form-item>
          <!-- 电话 -->
          <el-form-item
            label="电话"
            prop="mobile"
          >
            <el-input v-model="addRuleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addUser"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->

      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="editDialogClosed"
      >
        <!-- 内容区域 -->
        <el-form
          :model="editForm"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名">
            <el-input
              v-model="editForm.username"
              disabled
            ></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <!-- 电话 -->
          <el-form-item
            label="电话"
            prop="mobile"
          >
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="editUser"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色弹出框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <div>
          <p>当前的用户名 : {{this.UserInfo.username}}</p>
          <p>当前的角色 : {{this.UserInfo.role_name}}</p>
          <p>角色选择 :
            <el-select
              v-model="RolevalueId"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in RolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>

        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="setRolesDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitRolesInfo"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  // 自动刷新
  inject: ['reload'],
  data() {
    //自定义邮箱验证规则
    let checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        callback()
      } else {
        callback(new Error('输入的邮箱的格式不对,请重新输入'))
      }
    }
    //自定义电话验证个规则
    let checkMobile = (rule, value, callback) => {
      const regMobile = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      if (regMobile.test(value)) {
        callback()
      } else {
        callback(new Error('输入的电话格式不对,请重新输入'))
      }
    }
    return {
      queryUserInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      // 修改用户对话框关闭
      editDialogVisible: false,
      // 用户添加对话框关闭
      dialogVisible: false,
      //分配角色控制对话框
      setRolesDialogVisible: false,
      //分配角色的用户信息
      UserInfo:'',
      //角色列表
      RolesList:[],
      //用户选择的角色id值
      RolevalueId:'',
      //用户添加的数据
      addRuleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户数据
      editForm: '',
      // 用户添加验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryUserInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 默认会传入一个参数
    handleSizeChange(newSize) {
      this.queryUserInfo.pagesize = newSize
      //重新请求
      this.getUsersList()
    },
    handleCurrentChange(newCurrent) {
      this.queryUserInfo.pagenum = newCurrent
      this.getUsersList()
    },
    async userStatusChange(newUserInfo) {
      //发起修改请求
      const { data: res } = await this.$http.put(
        `users/${newUserInfo.id}/state/${newUserInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        //重新设置回原来的状态
        res.data.mg_state = !res.data.mg_state
        this.$message.error('修改状态失败')
      }
      this.$message.success('修改状态成功')
    },
    // 清除用户搜索框中的内容
    clearValueInfo() {
      this.getUsersList()
    },
    //关闭添加用户对话框
    handleClose(done) {
      done()
    },
    //当用户关闭添加用户对话框时重置表单内容
    addDialogClosed() {
      //$refs是form表单中的事件对象,resetFields是重置内容函数
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户,对整个表单预验证,并会返回一个Promise对象
    addUser() {
      this.$refs.addFormRef.validate(async vaild => {
        //vaild会返会一个boolean值
        if (!vaild) return
        //vaild是true发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addRuleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 成功之后关闭对话框
        this.dialogVisible = false
        // 将表单内容重置
        this.addDialogClosed();
        // 自动刷新
        this.reload();
      })
    },
    // 修改用户信息,弹出对话框
   async editUserModel(id) {
       const {data: res} = await this.$http.get(`users/${id}`);
       if(res.meta.status !== 200){
         return this.$message.error("获取信息失败")
       }
       this.editForm = res.data;
      //对话框
      this.editDialogVisible = true;
    },
    //修改用户信息重置表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async vaild => {
        if(!vaild) return;
        const {data: res} = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        });
        if(res.meta.status !== 200) {
          return this.$message.error("修改信息失败")
        }
        this.$message.success("修改用户成功");
        //成功之后关闭对话框
        this.editDialogVisible = false;
        // 自动刷新
        this.reload();
      })
    },
    //删除单个用户
   async deleteUsers (id) {
      //发起请求删除单个用户
     const {data: res} = await this.$http.delete(`users/${id}`);
     if(res.meta.status !== 200) {
       return this.$message.error(res.meta.msg);
     }
     this.$message.success(res.meta.msg);
     //自动刷新
     this.reload();
    },
    //分配角色弹出对话框
    async setRoles(Roles) {
      //保存用户信息
      this.UserInfo = Roles;
      //发起请求所用的角色名列表
      const {data: res} = await this.$http.get('roles');
      if(res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.RolesList = res.data;
      this.setRolesDialogVisible = true
    },
    //提交分配角色的信息
   async submitRolesInfo () {
    if(!this.RolevalueId) {
      return this.$message.error("请选择角色");
    }
     const {data: res} = await this.$http.put(`users/${this.UserInfo.id}/role`,{
       rid: this.RolevalueId
     });
     if(res.meta.status !== 200) {
       return this.$message.error(res.meta.msg);
     }
     this.$message.success(res.meta.msg);
     this.reload();
    }
  }
}
</script>
<style lang="less" scoped></style>
